/**
 * 技能条件评估器
 * 负责评估技能效果的触发条件
 */

import { EffectCondition, SkillEffectContext } from './SkillEffectTypes';
import { ServiceLogger } from '../../../../infrastructure/logging/UnifiedLogger';

/**
 * 条件评估结果
 */
interface ConditionEvaluationResult {
    /** 是否满足条件 */
    satisfied: boolean;
    /** 评估详情 */
    details?: string;
    /** 条件值（用于调试） */
    actualValue?: any;
    /** 期望值（用于调试） */
    expectedValue?: any;
}

/**
 * 技能条件评估器
 */
export class SkillConditionEvaluator {
    private logger: ServiceLogger;
    
    // 条件评估器映射
    private conditionEvaluators = new Map<string, (condition: EffectCondition, context: SkillEffectContext) => Promise<ConditionEvaluationResult>>();

    constructor() {
        this.logger = new ServiceLogger('SkillConditionEvaluator');
        this.initializeBuiltinEvaluators();
    }

    /**
     * 评估多个条件
     */
    async evaluateConditions(conditions: EffectCondition[], context: SkillEffectContext): Promise<boolean> {
        if (!conditions || conditions.length === 0) {
            return true; // 无条件限制
        }

        const results: ConditionEvaluationResult[] = [];
        
        for (const condition of conditions) {
            try {
                const result = await this.evaluateCondition(condition, context);
                results.push(result);
                
                // 如果是AND逻辑，任一条件不满足则直接返回false
                if (!result.satisfied) {
                    this.logger.debug('Condition evaluation failed', {
                        metadata: {
                            conditionType: condition.type,
                            details: result.details,
                            actualValue: result.actualValue,
                            expectedValue: result.expectedValue
                        }
                    });
                    return false;
                }
                
            } catch (error) {
                this.logger.error(`Condition evaluation error: ${condition.type}`, undefined, error);
                return false;
            }
        }

        // 所有条件都满足
        return true;
    }

    /**
     * 评估单个条件
     */
    async evaluateCondition(condition: EffectCondition, context: SkillEffectContext): Promise<ConditionEvaluationResult> {
        const evaluator = this.conditionEvaluators.get(condition.type);
        
        if (!evaluator) {
            this.logger.warn(`Unknown condition type: ${condition.type}`);
            return {
                satisfied: false,
                details: `Unknown condition type: ${condition.type}`
            };
        }

        try {
            const result = await evaluator(condition, context);
            
            // 应用否定逻辑
            if (condition.negate) {
                result.satisfied = !result.satisfied;
                result.details = `Negated: ${result.details}`;
            }
            
            return result;
            
        } catch (error) {
            this.logger.error(`Condition evaluation failed: ${condition.type}`, undefined, error);
            return {
                satisfied: false,
                details: `Evaluation error: ${(error as Error).message}`
            };
        }
    }

    /**
     * 注册自定义条件评估器
     */
    registerConditionEvaluator(
        conditionType: string, 
        evaluator: (condition: EffectCondition, context: SkillEffectContext) => Promise<ConditionEvaluationResult>
    ): void {
        this.conditionEvaluators.set(conditionType, evaluator);
        this.logger.info(`Custom condition evaluator registered: ${conditionType}`);
    }

    /**
     * 获取支持的条件类型
     */
    getSupportedConditionTypes(): string[] {
        return Array.from(this.conditionEvaluators.keys());
    }

    /**
     * 预测条件评估结果（不执行副作用）
     */
    async predictConditionResult(condition: EffectCondition, context: SkillEffectContext): Promise<ConditionEvaluationResult> {
        // 创建只读上下文副本用于预测
        const readOnlyContext = this.createReadOnlyContext(context);
        return await this.evaluateCondition(condition, readOnlyContext);
    }

    // ==================== 私有方法 ====================

    /**
     * 初始化内置评估器
     */
    private initializeBuiltinEvaluators(): void {
        // 生命值阈值条件
        this.conditionEvaluators.set('health_threshold', async (condition, context) => {
            const { minPercent, maxPercent, targetType } = condition.params;
            
            let target = context.caster;
            if (targetType === 'target' && context.targets.length > 0) {
                target = context.targets[0];
            }
            
            const currentHp = target.component?.hp_now || 0;
            const maxHp = target.component?.getAttribute('最大生命值') || 1;
            const healthPercent = currentHp / maxHp;
            
            const satisfied = healthPercent >= (minPercent || 0) && healthPercent <= (maxPercent || 1);
            
            return {
                satisfied,
                details: `Health: ${(healthPercent * 100).toFixed(1)}% (required: ${((minPercent || 0) * 100).toFixed(1)}%-${((maxPercent || 1) * 100).toFixed(1)}%)`,
                actualValue: healthPercent,
                expectedValue: { min: minPercent, max: maxPercent }
            };
        });

        // 法力值阈值条件
        this.conditionEvaluators.set('mana_threshold', async (condition, context) => {
            const { minPercent, maxPercent, targetType } = condition.params;
            
            let target = context.caster;
            if (targetType === 'target' && context.targets.length > 0) {
                target = context.targets[0];
            }
            
            const currentMp = target.component?.mp_now || 0;
            const maxMp = target.component?.getAttribute('最大法力值') || 1;
            const manaPercent = currentMp / maxMp;
            
            const satisfied = manaPercent >= (minPercent || 0) && manaPercent <= (maxPercent || 1);
            
            return {
                satisfied,
                details: `Mana: ${(manaPercent * 100).toFixed(1)}% (required: ${((minPercent || 0) * 100).toFixed(1)}%-${((maxPercent || 1) * 100).toFixed(1)}%)`,
                actualValue: manaPercent,
                expectedValue: { min: minPercent, max: maxPercent }
            };
        });

        // 目标数量条件
        this.conditionEvaluators.set('target_count', async (condition, context) => {
            const { minCount, maxCount, aliveOnly } = condition.params;
            
            let targets = context.targets;
            if (aliveOnly) {
                targets = targets.filter(t => !t.component?.isDie());
            }
            
            const targetCount = targets.length;
            const satisfied = targetCount >= (minCount || 0) && targetCount <= (maxCount || Infinity);
            
            return {
                satisfied,
                details: `Target count: ${targetCount} (required: ${minCount || 0}-${maxCount || 'unlimited'})`,
                actualValue: targetCount,
                expectedValue: { min: minCount, max: maxCount }
            };
        });

        // 暴击条件
        this.conditionEvaluators.set('critical_hit', async (condition, context) => {
            const { requiredCritical } = condition.params;
            const isCritical = context.battleContext?.isCritical || false;
            
            const satisfied = requiredCritical ? isCritical : !isCritical;
            
            return {
                satisfied,
                details: `Critical hit: ${isCritical} (required: ${requiredCritical})`,
                actualValue: isCritical,
                expectedValue: requiredCritical
            };
        });

        // 击杀条件
        this.conditionEvaluators.set('kill', async (condition, context) => {
            const { targetMustDie } = condition.params;
            const targetKilled = context.battleContext?.targetKilled || false;
            
            const satisfied = targetMustDie ? targetKilled : !targetKilled;
            
            return {
                satisfied,
                details: `Target killed: ${targetKilled} (required: ${targetMustDie})`,
                actualValue: targetKilled,
                expectedValue: targetMustDie
            };
        });

        // 技能等级条件
        this.conditionEvaluators.set('skill_level', async (condition, context) => {
            const { minLevel, maxLevel } = condition.params;
            const skillLevel = context.skillData?.level || 1;
            
            const satisfied = skillLevel >= (minLevel || 1) && skillLevel <= (maxLevel || Infinity);
            
            return {
                satisfied,
                details: `Skill level: ${skillLevel} (required: ${minLevel || 1}-${maxLevel || 'max'})`,
                actualValue: skillLevel,
                expectedValue: { min: minLevel, max: maxLevel }
            };
        });

        // 属性值条件
        this.conditionEvaluators.set('attribute_value', async (condition, context) => {
            const { attributeName, minValue, maxValue, targetType } = condition.params;
            
            let target = context.caster;
            if (targetType === 'target' && context.targets.length > 0) {
                target = context.targets[0];
            }
            
            const attributeValue = target.component?.getAttribute(attributeName) || 0;
            const satisfied = attributeValue >= (minValue || 0) && attributeValue <= (maxValue || Infinity);
            
            return {
                satisfied,
                details: `${attributeName}: ${attributeValue} (required: ${minValue || 0}-${maxValue || 'unlimited'})`,
                actualValue: attributeValue,
                expectedValue: { min: minValue, max: maxValue }
            };
        });

        // 回合数条件
        this.conditionEvaluators.set('round_number', async (condition, context) => {
            const { minRound, maxRound } = condition.params;
            const currentRound = context.battleContext?.round || 1;
            
            const satisfied = currentRound >= (minRound || 1) && currentRound <= (maxRound || Infinity);
            
            return {
                satisfied,
                details: `Round: ${currentRound} (required: ${minRound || 1}-${maxRound || 'unlimited'})`,
                actualValue: currentRound,
                expectedValue: { min: minRound, max: maxRound }
            };
        });

        // 概率条件
        this.conditionEvaluators.set('probability', async (condition, context) => {
            const { chance } = condition.params;
            const randomValue = Math.random();
            const satisfied = randomValue < (chance || 0.5);
            
            return {
                satisfied,
                details: `Probability check: ${(randomValue * 100).toFixed(1)}% vs ${((chance || 0.5) * 100).toFixed(1)}%`,
                actualValue: randomValue,
                expectedValue: chance
            };
        });

        // 自定义条件（通过JavaScript表达式）
        this.conditionEvaluators.set('custom', async (condition, context) => {
            const { expression } = condition.params;
            
            if (!expression) {
                return {
                    satisfied: false,
                    details: 'Missing custom expression'
                };
            }
            
            try {
                // 创建安全的评估环境
                const evaluationContext = {
                    caster: context.caster,
                    targets: context.targets,
                    skillData: context.skillData,
                    battleContext: context.battleContext,
                    Math,
                    // 添加常用的辅助函数
                    random: Math.random,
                    min: Math.min,
                    max: Math.max
                };
                
                // 使用Function构造器创建安全的表达式评估器
                const evaluator = new Function(...Object.keys(evaluationContext), `return ${expression}`);
                const result = evaluator(...Object.values(evaluationContext));
                
                return {
                    satisfied: Boolean(result),
                    details: `Custom expression: ${expression} = ${result}`,
                    actualValue: result,
                    expectedValue: true
                };
                
            } catch (error) {
                return {
                    satisfied: false,
                    details: `Custom expression error: ${(error as Error).message}`
                };
            }
        });

        this.logger.info(`Initialized ${this.conditionEvaluators.size} built-in condition evaluators`);
    }

    /**
     * 创建只读上下文
     */
    private createReadOnlyContext(context: SkillEffectContext): SkillEffectContext {
        // 创建深拷贝，避免在预测时修改原始上下文
        return JSON.parse(JSON.stringify(context));
    }
}
